package cn.zhoutao.org.service.impl;

import cn.zhoutao.basic.base.service.impl.BaseServiceImpl;
import cn.zhoutao.org.domain.Department;
import cn.zhoutao.org.mapper.DepartmentMapper;
import cn.zhoutao.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;

    @Transactional
    @Override
    public void save(Department department) {
        departmentMapper.save(department);//返回自增id
        this.update(department);
    }

    /**
     *
     * @param department
     */
    @Transactional
    @Override
    public void update(Department department) {
        String dirPath="";
        if(department.getDirPath()==null){
            //新增的就是顶级部门，自己就是祖宗
            dirPath="/"+department.getId();
        }else{
            //新增的非顶级部门有祖宗，找上级部门的dirpath+/自己的id
            Department parent = departmentMapper.loadById(department.getParent().getId());
            dirPath=parent.getDirPath()+"/"+department.getId();

        }
        department.setDirPath(dirPath);
        departmentMapper.update(department);
    }


    /**
     * 无限极树
     * @return
     */
    @Override
    public List<Department> queryTree() {
        //1.一次性查询出所有数据，放到内存 all
        List<Department> departments = departmentMapper.loadAll();
        HashMap<Long, Department> allDepts = new HashMap<>();
        for (Department department:departments){
            allDepts.put(department.getId(),department);
        }

        List<Department> firstDepts = new ArrayList<>();//登记部门
        for(Department temp:departments){
            if(temp.getParent_id()==null){
                // 2.从所有数据中找出第一层级 firstCourseType   我们需要返回的最外数据
                firstDepts.add(temp);
            }else{
                //3.只要不是第一层级的，找自己的上级，并将自己放入上级的children中
                Department parent = allDepts.get(temp.getParent_id());
                if(parent!=null){
                    parent.getChildren().add(temp);
                }
            }
        }

        return firstDepts;
    }
}
